<?php
namespace src;
use classlib\input;
use src\logic\Cadmin;
use classlib\core as C;
use classlib\core\controller;
class Cconfig extends controller {
	public function main() {
		$view   = C\view::inst('extjs');
		$userid = Cadmin::chkaccess($view);
		$view->assign_by_ref('title', Cadmin::$name);
		$view->display('core/config.ext.js');
	}
	
	/**
	 * 获取用户资料列表
	 */
	public function dolist() {
		$view   = C\view::inst('json');
		Cadmin::chkaccess($view);
		$where  = array();
		$key    = input::get_post('key');
		if ($key && !empty($key)) {
			$where[] = array('`key`', '%'.$key.'%', \classlib\orm::OP_LIKE);
		}
		list($start, $limit, $sort) = Cadmin::offset();
		$orm    = C\model::load('main.sys.config');
		$total  = $orm->get_total($where);
		$list   = array();
		if ($total > 0) {
			$list = $orm->get_list($start, $limit, $where, '*', $sort);
			foreach ($list as &$item) {
				$item['stime'] = date('Y-m-d H:i:s', $item['stime']);
			}
		}
		$view->assign_by_ref('total', $total);
		$view->assign_by_ref('dataset', $list);
		$view->display();
	}
	
	/**
	 * @desc    保存配置资料信息
	 * @doc     保存配置
	 * @access  需要授权
	 */
	public function dosave() {
		$view   = C\view::inst('json');
		Cadmin::chkaccess($view);
		$filter = new \classlib\validator\auditor();
		$lang   = C\lang::inst('adm');
		$filter->lang($lang);
		$data   = array();
		try {
			$data['key']  = $filter->reset('key')->required()->match('/^[0-9a-z\@\_\-]{1,63}$/')->run();
			$data['name'] = $filter->reset('name')->required()->minlen(1)->run();
			$data['value']= $filter->reset('value')->required()->minlen(1)->run();
			$data['memo'] = $filter->reset('memo')->required()->minlen(1)->run();
		} catch (\classlib\validator\AuditorException $e) {
			$view->assign_error($e->getField(), $e->getMessage());
		} catch (\Exception $e) {
			$view->assign_error($e->getCode(), $e->getMessage());
		}
		$id    = (int)input::get_post('id');
		$orm   = C\model::load('main.sys.config');
		$item  = $orm->get_item(array('`key`'=>$data['key']));
		if ($item && $item['id'] != $id) {
			$view->assign_error('key', $lang->txt('common', '40003', 'key', $data['key']));
		}
		$data['stime'] = C\config::$nowtime;
		($id > 0)? $orm->save($id, $data):$orm->new_one($data);
		Cadmin::log2db(C\view::inst('xml')->array2xml($data));
		$view->display();
	}
	
	/**
	 * @desc    删除配置资料信息
	 * @doc     删除配置
	 * @access  需要授权
	 */
	public function doremove() {
		$view = C\view::inst('json');
		Cadmin::chkaccess($view);
		$ids  = input::post('ids');
		$ids  = explode(',', $ids);
		if(!is_array($ids)) {
			$ids = array($ids);
		}
		foreach ($ids as $id) {
			if (is_numeric($id) && $id > 0) {
				C\model::load('main.sys.config')->delete($id);
			}
		}
		$view->display();
	}
}